package com.harisucici.skywarp;

import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;

import java.io.File;

/**
 * Created by harisucici on 2021/1/13
 * Class description:
 *
 * @author liuchenxi
 */
public class SkywarpObserver {
    private static SkywarpObserver skywarpObserver;
    private final HandlerThread handlerThread;
    private final Handler handler;
    private SkywarpListener listener;
    private Context context;
    private static final String TAG = "SkywarpObserver";
    private static final String EXTERNAL_CONTENT_URI_MATCHER = MediaStore.Images.Media.EXTERNAL_CONTENT_URI.toString();
    private static final String[] PROJECTION = new String[]{
            MediaStore.Images.Media.DISPLAY_NAME, MediaStore.Images.Media.DATA,
            MediaStore.Images.Media.DATE_ADDED
    };
    private static final String SORT_ORDER = MediaStore.Images.Media.DATE_ADDED + " DESC";
    private ContentResolver mContentResolver;
    private ContentObserver mContentObserver;

    private SkywarpObserver() {
        handlerThread = new HandlerThread("content_observer");
        handlerThread.start();
        handler = new Handler(handlerThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                listener.editFile((File) msg.obj);
                /*File file = (File) msg.obj;
                String s = file.getPath();
                Glide.with(context).asBitmap().load(file).into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        int height = resource.getHeight();
                        int width = resource.getWidth();
                        String s=resource.toString();
                        Log.e("bit",height+"::"+width);
                        Bitmap bitmap2 = addTextWatermark(resource, "大傻逼", 200, Color.RED, width, height, true);
                        save(bitmap2, file, Bitmap.CompressFormat.JPEG, true);
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {
                    }
                });
//                file.delete();
                context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile((File) msg.obj)));*/
            }
        };
    }

    public static synchronized SkywarpObserver getInstance() {
        if (skywarpObserver == null) {
            skywarpObserver = new SkywarpObserver();
        }
        return skywarpObserver;
    }

    public void startObserve(Context context, SkywarpListener listener) {
        this.listener = listener;
        this.context = context;
        skywarpObserver.register();

    }

    public void stopObserve() {
        skywarpObserver.unregister();
    }

    private void register() {
        mContentResolver = context.getContentResolver();
        mContentObserver = new ContentObserver(handler) {
            @Override
            public void onChange(boolean selfChange, Uri uri) {
                Log.d(TAG, "onChange: " + selfChange + ", " + uri.toString());
//                if (uri.toString().matches(EXTERNAL_CONTENT_URI_MATCHER)) {
                if (uri.toString().contains(EXTERNAL_CONTENT_URI_MATCHER)) {
                    Cursor cursor = null;
                    try {
                        cursor = mContentResolver.query(uri, PROJECTION, null, null, SORT_ORDER);
                        if (cursor != null && cursor.moveToFirst()) {
                            String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                            long dateAdded = cursor.getLong(cursor.getColumnIndex(MediaStore.Images.Media.DATE_ADDED));
                            long currentTime = System.currentTimeMillis();
                            Log.d(TAG, "path: " + path + ", dateAdded: " + dateAdded + ", currentTime: " + currentTime);
//                            Log.d(TAG, "matchPath(path): " + matchPath(path) + ", matchAddTime(dateAdded): " + matchAddTime(dateAdded) + ", matchSize(path): " + matchSize(path));
                            if (matchPath(path) && matchAddTime(dateAdded)) {
                                // screenshot added!
                                File file = new File(path);
                                Message message = Message.obtain();
                                message.obj = file;
                                //set4huawei
                                handler.sendMessageDelayed(message, 250);
                            }
                        }
                    } catch (Exception e) {
                        Log.d(TAG, "Exception" + e.toString());
                    } finally {
                        if (cursor != null) {
                            cursor.close();
                        }
                    }
                }
                super.onChange(selfChange, uri);
            }
        };
        mContentResolver.registerContentObserver(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true,
                mContentObserver);
    }

    private void unregister() {
        context.getContentResolver().unregisterContentObserver(mContentObserver);
    }

    private boolean matchAddTime(long addTime) {
        return System.currentTimeMillis() - addTime * 1000 < 1500;
    }

   /* private boolean matchSize(String filePath) {
        int w = ScreenUtil.getScreenWidth(context);
        int h = ScreenUtil.getScreenWidth(context);

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        return w >= options.outWidth && h >= options.outHeight;
    }*/

    // imagepath contain screenshot
    private boolean matchPath(String filePath) {
        String lower = filePath.toLowerCase();
        return lower.contains("screenshot");
    }






}